//
//  CollectViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/7/11.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "CollectViewController.h"
#import "ZuoPinCell.h"
#import "XiangQingViewController.h"
#import "FindLayout.h"
#import "IGGetCollectApi.h"
#import "IGDatabaseApi.h"
#import "IGMydeletApi.h"
#import "IGiGalleryListApi.h"
#import "IGiGalleryPushApi.h"
#import "IGPushiGalleryListVC.h"

@interface CollectViewController () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    UICollectionView *collect;
    UIView *nonView;
    
    NSMutableArray *selArr;
    BOOL isEdit;
    UIView *tabbar;
    
    NSString *p_idsStr;
    NSString *pay_type;
    NSMutableArray *imageUrlArr;
    NSString *uId;//用户id
    IGArtWorkModel *info ;
    
    UIButton *right;
    NSInteger selCount;
    
    NSString *pushSuccess;
    
}
@property(nonatomic,strong)IGGetCollectApi *collectApi;
@property(nonatomic,strong)IGMydeletApi*deletApi;
@property (nonatomic, strong) IGiGalleryListApi *igalleryListApi;
@property (nonatomic, strong) NSArray *iGalleryListArr;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, copy) NSString *pageNumber;
@property (nonatomic, copy) NSString *pageSize;
@property (nonatomic, copy) NSString *queryTime;


@end

@implementation CollectViewController

#pragma mark-懒加载
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[NSMutableArray array];
    }
    return _dataArr;
}
-(NSArray *)iGalleryListArr{
    if (!_iGalleryListArr) {
        _iGalleryListArr=[NSArray array];
    }
    return _iGalleryListArr;
}
#pragma mark-生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
     AdjustsScrollViewInsetNever(self, collect);
//    self.title=@"我的收藏";
    self.title=NSLocalizedString(@"Favorites", nil);
    self.view.backgroundColor =[UIColor c2Color];
    
    FindLayout *layout = [[FindLayout alloc] init];
    collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, KSCREENWIDTH, self.view.frame.size.height) collectionViewLayout:layout];
    collect.backgroundColor = [UIColor clearColor];
    collect.delegate = self;
    collect.dataSource = self;
    if (@available(iOS 11.0, *)) {
        collect.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        collect.scrollIndicatorInsets = collect.contentInset;
    }
    collect.alwaysBounceVertical = YES;
    [collect registerClass:[ZuoPinCell class] forCellWithReuseIdentifier:@"collectArtCell"];
    
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
    [collect addGestureRecognizer:longTap];
    [self.view addSubview:collect];
    
    nonView=[[UIView alloc]initWithFrame:CGRectMake(0, 80, KSCREENWIDTH, 100)];
    nonView.backgroundColor=[UIColor clearColor];
    UILabel *nonLable=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 60)];
    nonLable.center=nonView.center;
//    nonLable.text=@"您还没有收藏任何公开作品\n快去收藏吧~";
    nonLable.text=NSLocalizedString(@"No Collection Saved Yet. Go Get Some Now.", nil);
    nonLable.numberOfLines=2;
    nonLable.textAlignment=NSTextAlignmentCenter;
    nonLable.font=[UIFont font16];
    nonLable.textColor=[UIColor blackColor];
    [nonView addSubview:nonLable];
    nonView.hidden=YES;
    [collect addSubview:nonView];

    right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 60, 50);
    [right.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
//    [right setTitle:@"取消" forState:UIControlStateSelected];
//    [right setTitle:@"选择" forState:UIControlStateNormal];
    [right setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateSelected];
    [right setTitle:NSLocalizedString(@"Select", nil) forState:UIControlStateNormal];
    [right setTitleColor:RGB(0, 170, 229) forState:UIControlStateNormal];
    [right addTarget:self action:@selector(canel) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];
    [self setIsEdit:NO];
    self.collectApi = [IGGetCollectApi new];
    [self firstPage];
    [self requestIGlist];
    @KWeakObj(self)
    [collect ig_setHeaderWithRefreshingBlock:^{
        [selfWeak firstPage];
    }];
}
- (void)firstPage
{
    _pageSize = @"10";
    _pageNumber = @"0";
    _queryTime = @"";
    [self requestDate];
}

-(void)requestDate{
    self.collectApi.pageNumber=_pageNumber;
    self.collectApi.pageSize=_pageSize;
    self.collectApi.queryTime=_queryTime;
    @KWeakObj(self)
    [self.collectApi startWithDecodeClass:[IGGetCollectResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [collect ig_endHeaderRefreshing];
        [collect ig_endFooterRefreshing];
        if (responseObject) {
            IGGetCollectResp *resp=responseObject;
            IGGetCollectModel *model=resp.data;
            if (model.lstWork&&model.lstWork.count>0) {
                [selfWeak setupFooter];
            }
            else
            {
//                [collect ig_endFooterRefreshingWithNoMoreData];
              }
            _queryTime = model.queryTime;
            if ([_pageNumber isEqualToString:@"0"]){
                _dataArr = [NSMutableArray arrayWithArray:model.lstWork];
                if (_dataArr.count==0) {
                    nonView.hidden=NO;
                    tabbar.hidden=YES;
                    right.userInteractionEnabled=NO;
                    collect.userInteractionEnabled=NO;
                }
            }
            else
            {
                if (model.lstWork.count==0) {
                    [collect ig_endFooterRefreshingWithNoMoreData];
                }
                [_dataArr addObjectsFromArray:model.lstWork];
                for (int i=0; i<model.lstWork.count; i++) {
                    [selArr addObject:@(NO)];
                }
            }
            [collect reloadData];
        }
        else
        {
            //空白页处理逻辑写在这里
        }
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if ([pushSuccess isEqualToString:@"1"]) {
        if (isEdit) {
            [self canel];
        }
        pushSuccess=@"0";
    }
    
}
- (void)setupFooter
{
    @KWeakObj(self)
    [collect ig_setFooterWithRefreshingBlock:^{
        _pageNumber = [NSString stringWithFormat:@"%ld", [_pageNumber integerValue] + 1];
//        if (isEdit) {
//            [self canel];
//        }
        [selfWeak requestDate];
    }];
}
- (void)scrollToTOP
{
    [collect setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  self.dataArr.count>0?self.dataArr.count:0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZuoPinCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectArtCell" forIndexPath:indexPath];
    cell.data=_dataArr[indexPath.item];
    cell.isEdit = isEdit;
    if (isEdit)
    {
        cell.isSel = [selArr[indexPath.item]boolValue] ;
    }
    [cell setNeedsLayout];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (isEdit)
    {
        NSMutableArray *selIndexArr = [NSMutableArray array];
        
        for (int i=0; i<selArr.count; i++) {
            selCount=selIndexArr.count ;
            [collect reloadData];
            NSNumber *s = selArr[i];
            if ([s boolValue]) {
                [selIndexArr addObject:@(i)];
            }
        }
        if (selIndexArr.count >= 8) {
            BOOL canel = NO;
            for (NSNumber *index in selIndexArr) {
                if (indexPath.item==[index integerValue]) {
                    canel = YES;
                    break;
                }
            }
            if (!canel) {
//                [self presentMessageTips:@"最多可选8张"];
                [self presentMessageTips:NSLocalizedString(@"Select no more than 8 pictures", nil)];
                return;
            }
        }
        BOOL sel = [selArr[indexPath.item] boolValue];
        [selArr removeObjectAtIndex:indexPath.item];
        [selArr insertObject:@(!sel) atIndex:indexPath.item];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [collect reloadData];
        });
    } else
    {
        IGArtWorkModel *list = _dataArr[indexPath.item];
        XiangQingViewController *vc = [[XiangQingViewController alloc] init];
        vc.p_id = list.aId;
        vc.isRoot = YES;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    IGArtWorkModel *base =_dataArr[indexPath.item];
    if ([base.plates integerValue]==1)
    {
        //横板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1080/1920));
    }
    else if ([base.plates integerValue]==2)
    {
        //坚板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1920/1080));
    }
    return CGSizeMake(0, 0);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 5, 5, 5);
}
#pragma mark-长按
- (void)longTap:(UIGestureRecognizer *)longTap {
    if (!isEdit) {
        [self setIsEdit:YES];
        
        selArr = [NSMutableArray array];
                for (int i=0; i<_dataArr.count; i++) {
                    [selArr addObject:@(NO)];
                }
        
        if (!tabbar) {
            tabbar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 49)];
            tabbar.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:tabbar];
            
            UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
            del.titleLabel.font = [UIFont systemFontOfSize:15];
            [del setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [del setTitle:@"删除" forState:UIControlStateNormal];
            [del setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
            [del setImage:[UIImage imageNamed:@"C-13-3"] forState:UIControlStateNormal];
            [del addTarget:self action:@selector(delModel:) forControlEvents:UIControlEventTouchUpInside];
            [del setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
            del.frame = CGRectMake(0, 0, KSCREENWIDTH/3, 49);
            [tabbar addSubview:del];
            
            UIButton *push = [UIButton buttonWithType:UIButtonTypeCustom];
            push.backgroundColor =[UIColor appColor];
            push.titleLabel.font = [UIFont systemFontOfSize:15];
            [push setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [push setTitle:@"推送到画屏" forState:UIControlStateNormal];
            [push setTitle:NSLocalizedString(@"Push to iGallery", nil) forState:UIControlStateNormal];
            [push addTarget:self action:@selector(pushPhoto:) forControlEvents:UIControlEventTouchUpInside];
            push.frame = CGRectMake(del.right, 0, KSCREENWIDTH/3*2, 49);
            [tabbar addSubview:push];
            
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, .5)];
            line.backgroundColor = [UIColor lightGrayColor];
            [tabbar addSubview:line];
        }
        tabbar.top = self.view.height;
        [UIView animateWithDuration:.2 animations:^{
            tabbar.bottom = self.view.height;
        } completion:^(BOOL finished) {
            collect.mj_header.hidden = YES;
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49*2+20, 0);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [collect reloadData];
            });
        }];
        
    }
}

#pragma mark-删除收藏作品
- (void)delModel:(UIButton *)btn {
    @KWeakObj(self)
    NSMutableArray *selIndexArr = [NSMutableArray array];
    for (int i=0; i<selArr.count; i++) {
        NSNumber *s = selArr[i];
        if ([s boolValue]) {
            [selIndexArr addObject:@(i)];
        }
    }
    
    if (selIndexArr.count==0) {
        //        [self presentMessageTips:@"至少选择一个作品"];
        [self presentMessageTips:NSLocalizedString(@"Select at least one Work", nil)];
        return;
    }
    NSMutableArray *infoArr = [NSMutableArray array];
    for (NSNumber *index in selIndexArr) {
        info = _dataArr[[index integerValue]];
        [infoArr addObject:info.aId];
    }
    NSString * p_idStr = [infoArr componentsJoinedByString:@","];
    [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"Notice", nil) message:NSLocalizedString(@"Confirm to delete this picture/these pictures?",nil) cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            self.deletApi=[[IGMydeletApi alloc]initWithWorksIds:p_idStr uId:[IGUser getUid]];
            [self.deletApi startWithDecodeClass:[IGMydeletResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                if (responseObject) {
                    [self canel];
                    [selfWeak firstPage];
                }
            }];
        }
    }];

}
#pragma mark-推送的作品
- (void)pushPhoto:(UIButton *)btn
{
    NSMutableArray *selIndexArr = [NSMutableArray array];
    for (int i=0; i<selArr.count; i++) {
        NSNumber *s = selArr[i];
        if ([s boolValue]) {
            [selIndexArr addObject:@(i)];
        }
    }
    
    if (selIndexArr.count==0) {
//        [self presentMessageTips:@"至少选择一个作品"];
        [self presentMessageTips:NSLocalizedString(@"Select at least one Work", nil)];
        return;
    }
    
    NSMutableArray *infoArr = [NSMutableArray array];
    for (NSNumber *index in selIndexArr) {
        IGArtWorkModel *work = _dataArr[[index integerValue]];
        [infoArr addObject:work];
    }
    
    if (self.iGalleryListArr.count == 0) {
//        [self presentMessageTips:@"当前无绑定设备"];
        [self presentMessageTips:NSLocalizedString(@"No linked device found", nil)];
    } else if (self.iGalleryListArr.count == 1) {
         [self pushToDev:infoArr];
    } else {
        IGPushiGalleryListVC *listVC = [[IGPushiGalleryListVC alloc] initWithType:IGPushiGalleryTypeNN];
        listVC.recommendArr = infoArr;
        listVC.successBlock = ^(NSString *strValue) {
            pushSuccess=strValue;
        };
        [UIViewController ig_pushViewController:listVC animated:YES];
    }
}
#pragma mark-请求绑定设备列表
-(void)requestIGlist {
    self.igalleryListApi = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
    __weak typeof(self) weakSelf = self;
    [self.igalleryListApi startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGiGalleryListResp *resp = responseObject;
            IGiGalleryListModel *model = resp.data;
            weakSelf.iGalleryListArr = [NSArray arrayWithArray:model.equs];
        }
    }];
}
#pragma mark-推送请求
- (void)pushToDev:(NSArray *)infoArr
{
    NSMutableArray *aIds = [NSMutableArray array];
    for (IGArtWorkModel *info in infoArr) {
        [aIds addObject:info.aId];
    }
    IGiGalleryEqu *equ = self.iGalleryListArr[0];
    IGiGalleryPushApi *pushApi = [[IGiGalleryPushApi alloc] initWithMacIds:@[equ.macId] pIds:aIds];
//    [self presentMessageTips:@"正在推送..."];
    [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
    [pushApi startWithDecodeClass:[IGiGalleryPushResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
//            [self presentMessageTips:@"推送成功..."];
            [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
            [self canel];
            [self firstPage];
        
        }
    }];
}

- (void)pushModel:(UIButton *)btn {
    NSMutableArray *selIndexArr = [NSMutableArray array];
    for (int i=0; i<selArr.count; i++) {
        NSNumber *s = selArr[i];
        if ([s boolValue]) {
            [selIndexArr addObject:@(i)];
        }
    }
    
    if (selIndexArr.count==0) {
//        [self presentMessageTips:@"至少选择一个作品"];
        [self presentMessageTips:NSLocalizedString(@"Select at least one Work", nil)];
        return;
    }
    imageUrlArr = [NSMutableArray array];
    
    NSMutableArray *payArr = [NSMutableArray array];
    NSMutableArray *infoArr = [NSMutableArray array];
        for (NSNumber *index in selIndexArr) {
            info = _dataArr[[index integerValue]];
            [infoArr addObject:info.aId];
            [payArr addObject:info.plates];
            [imageUrlArr addObject:info.image];
        }
    
    p_idsStr = nil;
    p_idsStr = [infoArr componentsJoinedByString:@"-"];
    
    pay_type = nil;
    pay_type = [payArr componentsJoinedByString:@"_"];
    
    //    [baseModel app_php_User_equipment_list];
}

- (void)setIsEdit:(BOOL)edit
{
    [right setSelected:edit];
    isEdit = edit;
}

#pragma mark-点击取消
- (void)canel
{
    if ([right isSelected]) {
        [self setIsEdit:NO];
        [UIView animateWithDuration:.2 animations:^{
            tabbar.top = self.view.height;
        } completion:^(BOOL finished) {
            collect.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            collect.mj_header.hidden = NO;
            [collect reloadData];

        }];
    }else if(![right isSelected]){
        [self setIsEdit:YES];
        selArr = [NSMutableArray array];
                    for (int i=0; i<_dataArr.count; i++) {
                    [selArr addObject:@(NO)];
                      }
        if (!tabbar) {
            tabbar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 49)];
            tabbar.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:tabbar];
            
            UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
            del.titleLabel.font = [UIFont systemFontOfSize:15];
            [del setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [del setTitle:@"删除" forState:UIControlStateNormal];
            [del setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
            [del setImage:[UIImage imageNamed:@"C-13-3"] forState:UIControlStateNormal];
            [del addTarget:self action:@selector(delModel:) forControlEvents:UIControlEventTouchUpInside];
            [del setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
            del.frame = CGRectMake(0, 0, KSCREENWIDTH/3, 49);
            [tabbar addSubview:del];
            
            UIButton *push = [UIButton buttonWithType:UIButtonTypeCustom];
            push.backgroundColor =[UIColor appColor];
            push.titleLabel.font = [UIFont systemFontOfSize:15];
            [push setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [push setTitle:@"推送到画屏" forState:UIControlStateNormal];
            [push setTitle:NSLocalizedString(@"Push to iGallery", nil) forState:UIControlStateNormal];
            [push addTarget:self action:@selector(pushPhoto:) forControlEvents:UIControlEventTouchUpInside];
            push.frame = CGRectMake(del.right, 0, KSCREENWIDTH/3*2, 49);
            [tabbar addSubview:push];
            
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, .5)];
            line.backgroundColor = [UIColor lightGrayColor];
            [tabbar addSubview:line];
        }
        tabbar.top = self.view.height;
        [UIView animateWithDuration:.2 animations:^{
            tabbar.bottom = self.view.height;
        } completion:^(BOOL finished) {
            collect.mj_header.hidden = YES;
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [collect reloadData];
            });
        }];
    }
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
